package com.study;

import java.util.Arrays;

/**
 * @program: leetcode
 * @author: jzhou
 * @date: 2022-11-01 11:23
 * @version: 1.0
 * @description: 寻找数组中心下标
 *      解法一：其左侧所有元素相加和等于其右侧所有元素相加和，如果不存在这样的下标返回 -1
 *      解法二：2 * sum + curr = total
 *
 **/
public class ArrayCenterIndex {

	public static void main(String[] args) {
		System.out.println(centerIndex(new int[]{1,8,9,7,3,5,2,3,5}));
	}

	private static int centerIndex(int[] arr) {
		int total = Arrays.stream(arr).sum();

		for (int i = 0, sum = 0,len = arr.length; i < len; i++) {
			sum += arr[i];
			if (sum == total){
				return i;
			}
			total -= arr[i];
		}
		return -1;
	}

	private static int centerIndex1(int[] arr){
		int total = Arrays.stream(arr).sum();
		int sum = 0;
		for (int i = 0; i < arr.length; i++) {
			sum = sum + arr[i];
			if (sum == total){
				return i;
			}
			total = total - arr[i];
		}
		return -1;
	}
}
